<template>
  <div class="login-container">
    <!-- 成功提示 -->
    <div v-if="showSuccess" class="success-toast">
      <div class="success-content">
        <i class="success-icon">✓</i>
        <span>{{ successMessage }}</span>
      </div>
    </div>
    <!-- 左侧品牌展示区域 -->
    <div class="left-section">
      <div class="brand-content">
        <div class="logo-container">
          <img src="/前台Logo.png" alt="MOKA商店Logo" class="brand-logo" />
        </div>
        <h1 class="brand-title">MOKA商店</h1>
        <p class="brand-subtitle">一站式购物体验，品质生活从这里开始</p>
        <div class="features">
          <div class="feature-item">
            <i class="feature-icon">🛍️</i>
            <span>精选商品</span>
          </div>
          <div class="feature-item">
            <i class="feature-icon">🚚</i>
            <span>快速配送</span>
          </div>
          <div class="feature-item">
            <i class="feature-icon">🔒</i>
            <span>安全保障</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧登录区域 -->
    <div class="right-section">
      <div class="login-content">
        <!-- 忘记密码表单 -->
        <div v-if="isForgotPasswordMode" class="form-container">
          <div class="register-header">
            <h2>找回密码</h2>
            <p>请输入您的账户信息重置密码</p>
          </div>

          <form class="register-form" @submit.prevent="handleUpdatePassword">
            <div class="form-group">
              <input
                v-model="forgotPasswordForm.name"
                type="text"
                placeholder="用户名"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.phone"
                type="tel"
                placeholder="手机号码"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.newPassword"
                type="password"
                placeholder="新密码（6-10位）"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="forgotPasswordForm.confirmPassword"
                type="password"
                placeholder="确认新密码"
                class="form-input"
                required
              />
            </div>

            <button type="submit" class="register-button" :disabled="loading">
              <span v-if="loading">修改中...</span>
              <span v-else>重置密码</span>
            </button>
          </form>

          <div class="login-link">
            返回登录？<a href="#" @click="goBackToLogin">立即登录</a>
          </div>
        </div>

        <!-- 登录表单 -->
        <div v-if="!isRegisterMode && !isForgotPasswordMode" class="form-container">
          <div class="login-header">
            <h2>客户登录</h2>
            <p>欢迎回来，请登录您的账户</p>
          </div>

          <form class="login-form" @submit.prevent="handleLogin">
            <div class="form-group">
              <input
                v-model="loginForm.username"
                type="text"
                placeholder="用户名"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-options">
              <label class="checkbox-wrapper">
                <input v-model="loginForm.rememberMe" type="checkbox" />
                <span class="checkmark"></span>
                记住我
              </label>
              <a href="#" class="forgot-password" @click.prevent="goToForgotPassword">忘记密码？</a>
            </div>

            <button type="submit" class="login-button" :disabled="loading">
              <span v-if="loading">登录中...</span>
              <span v-else>登录</span>
            </button>
          </form>

          <div class="register-link">
            还没有账户？<a href="#" @click="goToRegister">立即注册</a>
          </div>

          <div class="social-login">
            <div class="divider">
              <span>或使用以下方式登录</span>
            </div>
            <div class="social-buttons">
              <button class="social-btn wechat">
                <i class="social-icon">💬</i>
                微信登录
              </button>
              <button class="social-btn qq">
                <i class="social-icon">🐧</i>
                QQ登录
              </button>
            </div>
          </div>

          <!-- 商家登录入口 -->
          <div class="seller-entrance">
            <div class="divider">
              <span>商家用户</span>
            </div>
            <button class="seller-login-btn" @click="goToSellerLogin">
              <i class="seller-icon">🏪</i>
              商家登录入口
            </button>
          </div>
        </div>

        <!-- 注册表单 -->
        <div v-else-if="isRegisterMode" class="form-container">
          <div class="register-header">
            <h2>用户注册</h2>
            <p>创建您的账户，开始购物之旅</p>
          </div>

          <form class="register-form" @submit.prevent="handleRegister">
            <div class="form-group">
              <input
                v-model="registerForm.name"
                type="text"
                placeholder="用户名"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.phone"
                type="tel"
                placeholder="手机号码"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.password"
                type="password"
                placeholder="密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-group">
              <input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                class="form-input"
                required
              />
            </div>

            <div class="form-options">
              <label class="checkbox-wrapper">
                <input v-model="registerForm.agreeTerms" type="checkbox" />
                <span class="checkmark"></span>
                我同意<a href="#" class="terms-link">用户协议</a>和<a href="#" class="terms-link">隐私政策</a>
              </label>
            </div>

            <button type="submit" class="register-button" :disabled="loading">
              <span v-if="loading">注册中...</span>
              <span v-else>注册</span>
            </button>
          </form>

          <div class="login-link">
            已有账户？<a href="#" @click="goToLogin">立即登录</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register as apiRegister, login as apiLogin, updatePassword as apiUpdatePassword } from '@/api/user'

export default {
  name: 'CustomerLogin',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const isRegisterMode = ref(false) // 控制显示登录还是注册表单
    const isForgotPasswordMode = ref(false) // 控制显示忘记密码表单
    const successMessage = ref('')
    const showSuccess = ref(false)

    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    })

    const registerForm = reactive({
      name: '',
      phone: '',
      password: '',
      confirmPassword: '',
      agreeTerms: false
    })

    const forgotPasswordForm = reactive({
      name: '',
      phone: '',
      newPassword: '',
      confirmPassword: ''
    })

    const handleLogin = async () => {
      if (!loginForm.username || !loginForm.password) {
        ElMessage.warning('请填写用户名和密码')
        return
      }

      loading.value = true

      try {
        const result = await apiLogin({
          name: loginForm.username,
          password: loginForm.password
        })
        if (result.status) {
          const userData = result?.data ?? {}
          const roles = userData?.roles ?? []
          const token = userData?.token

          // 简化存储结构：只存储roles数组和token
          localStorage.setItem('userRoles', JSON.stringify(roles))
          localStorage.setItem('userToken', token)

          console.log('登录成功，存储的数据：')
          console.log('roles:', roles)
          console.log('token:', token)

          // 显示成功提示（3秒后自动消失）
          showSuccessMessage('登录成功！')

          // 延迟跳转到商品首页
          setTimeout(() => {
            router.push('/')
          }, 800)
        } else {
          ElMessage.error(result.message || '登录失败，请检查用户名或密码')
        }
      } catch (error) {
        console.error('登录请求失败:', error)
        ElMessage.error(error.message || '网络错误，请检查后端服务是否启动')
      } finally {
        loading.value = false
      }
    }

    const handleRegister = async () => {
      if (!registerForm.name || !registerForm.phone || !registerForm.password) {
        ElMessage.warning('请填写所有必填字段')
        return
      }

      if (registerForm.password !== registerForm.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致')
        return
      }

      if (!registerForm.agreeTerms) {
        ElMessage.warning('请同意用户协议')
        return
      }

      loading.value = true

      try {
        const result = await apiRegister({
          name: registerForm.name,
          phone: registerForm.phone,
          password: registerForm.password
        })

        if (result.status) {
          showSuccessMessage('注册成功！')

          // 延迟切换到登录模式
          setTimeout(() => {
            isRegisterMode.value = false // 注册成功后切换到登录模式
          }, 1500)
          // 清空表单
          registerForm.name = ''
          registerForm.phone = ''
          registerForm.password = ''
          registerForm.confirmPassword = ''
          registerForm.agreeTerms = false
        } else {
          ElMessage.error(result.message || '注册失败，请重试')
        }
      } catch (error) {
        console.error('注册请求失败:', error)
        ElMessage.error(error.message || '网络错误，请检查后端服务是否启动')
      } finally {
        loading.value = false
      }
    }

    const goToRegister = () => {
      isRegisterMode.value = true
    }

    const goToLogin = () => {
      isRegisterMode.value = false
      isForgotPasswordMode.value = false
    }

    const showSuccessMessage = (message) => {
      successMessage.value = message
      showSuccess.value = true

      // 3秒后自动隐藏
      setTimeout(() => {
        showSuccess.value = false
      }, 3000)
    }

    const goToSellerLogin = () => {
      router.push('/seller-login')
    }

    const goToForgotPassword = () => {
      isForgotPasswordMode.value = true
      isRegisterMode.value = false
    }

    const goBackToLogin = () => {
      isForgotPasswordMode.value = false
      isRegisterMode.value = false
    }

    const handleUpdatePassword = async () => {
      // 表单验证
      if (!forgotPasswordForm.name) {
        ElMessage.warning('请输入用户名')
        return
      }
      if (!forgotPasswordForm.phone) {
        ElMessage.warning('请输入手机号码')
        return
      }
      // 简单的手机号格式验证
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(forgotPasswordForm.phone)) {
        ElMessage.warning('请输入正确的手机号码格式')
        return
      }
      if (!forgotPasswordForm.newPassword) {
        ElMessage.warning('请输入新密码')
        return
      }
      if (forgotPasswordForm.newPassword.length < 6 || forgotPasswordForm.newPassword.length > 10) {
        ElMessage.warning('新密码长度必须为6-10位')
        return
      }
      if (forgotPasswordForm.newPassword !== forgotPasswordForm.confirmPassword) {
        ElMessage.warning('两次输入的密码不一致')
        return
      }

      loading.value = true

      try {
        const result = await apiUpdatePassword({
          name: forgotPasswordForm.name,
          phone: forgotPasswordForm.phone,
          newPassword: forgotPasswordForm.newPassword
        })

        if (result.status) {
          showSuccessMessage('密码修改成功！')

          // 延迟返回登录页
          setTimeout(() => {
            isForgotPasswordMode.value = false
            // 清空表单
            forgotPasswordForm.name = ''
            forgotPasswordForm.phone = ''
            forgotPasswordForm.newPassword = ''
            forgotPasswordForm.confirmPassword = ''
          }, 1500)
        } else {
          ElMessage.error(result.message || '密码修改失败，请重试')
        }
      } catch (error) {
        console.error('密码修改请求失败:', error)
        ElMessage.error(error.message || '网络错误，请检查后端服务是否启动')
      } finally {
        loading.value = false
      }
    }

    return {
      loginForm,
      registerForm,
      forgotPasswordForm,
      loading,
      isRegisterMode,
      isForgotPasswordMode,
      successMessage,
      showSuccess,
      handleLogin,
      handleRegister,
      handleUpdatePassword,
      goToRegister,
      goToLogin,
      goToForgotPassword,
      goBackToLogin,
      goToSellerLogin,
      showSuccessMessage
    }
  }
}
</script>

<style>
/* 全局重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}

/* 登录容器 */
.login-container {
  display: flex;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

/* 左侧品牌区域 */
.left-section {
  width: 38vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.brand-content {
  text-align: center;
  max-width: 90%;
  padding: 20px;
}

.logo-container {
  margin-bottom: 30px;
}

.brand-logo {
  width: 120px;
  height: 120px;
  object-fit: contain;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.1);
  padding: 10px;
  backdrop-filter: blur(10px);
}

.brand-title {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 20px;
  letter-spacing: 2px;
}

.brand-subtitle {
  font-size: 18px;
  margin-bottom: 40px;
  opacity: 0.9;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 15px 20px;
  border-radius: 10px;
  backdrop-filter: blur(10px);
}

.feature-icon {
  font-size: 24px;
}

/* 右侧登录区域 */
.right-section {
  width: 62vw;
  height: 100vh;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  flex-shrink: 0;
}

.login-content {
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  font-size: 32px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 16px;
}

/* 注册表单头部 */
.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h2 {
  font-size: 32px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 600;
}

.register-header p {
  color: #666;
  font-size: 16px;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

/* 注册表单 */
.register-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  height: 50px;
  padding: 0 15px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
  background: #f8f9fa;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input::placeholder {
  color: #999;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-wrapper input[type="checkbox"] {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 30px;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

/* 注册按钮 */
.register-button {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 30px;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.register-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.register-link {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  font-size: 14px;
}

.register-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

/* 登录链接 */
.login-link {
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  font-size: 14px;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 条款链接 */
.terms-link {
  color: #667eea;
  text-decoration: none;
}

.terms-link:hover {
  text-decoration: underline;
}

.social-login {
  margin-top: 30px;
}

.divider {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: white;
  padding: 0 20px;
  color: #999;
  font-size: 14px;
}

.social-buttons {
  display: flex;
  gap: 15px;
}

.social-btn {
  flex: 1;
  height: 45px;
  border: 2px solid #e4e7ed;
  background: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.social-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.social-btn.wechat:hover {
  border-color: #07c160;
  color: #07c160;
}

.social-btn.qq:hover {
  border-color: #12b7f5;
  color: #12b7f5;
}

.social-icon {
  font-size: 18px;
}

/* 商家登录入口样式 */
.seller-entrance {
  margin-top: 30px;
}

.seller-login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  color: white;
  border: none;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 16px;
  font-weight: 500;
}

.seller-login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(30, 60, 114, 0.3);
}

.seller-icon {
  font-size: 20px;
}

/* 成功提示样式 */
.success-toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  animation: slideDown 0.3s ease-out;
}

.success-content {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  color: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(82, 196, 26, 0.3);
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 500;
  backdrop-filter: blur(10px);
}

.success-icon {
  font-size: 18px;
  font-weight: bold;
  background: rgba(255, 255, 255, 0.2);
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }

  .left-section,
  .right-section {
    width: 100vw;
  }

  .left-section {
    height: 30vh;
  }

  .right-section {
    height: 70vh;
    padding: 20px;
  }

  .brand-title {
    font-size: 36px;
  }

  .features {
    flex-direction: row;
    justify-content: space-around;
  }

  .feature-item {
    flex-direction: column;
    text-align: center;
    padding: 10px;
    font-size: 14px;
  }
}
</style>
